package rsa

import (
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/core"
	"gitee.com/binny_w/go-util"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"time"
)

var MdlRsa *partner.CommonModel
var instance *util.RsaKeys

func init() {
	core.WaitCore.Wait()

	if err := util.Retry(999, time.Millisecond, func() error {
		var pubKey, priKey []byte
		var err error
		if pubKey, priKey, err = util.RsaGenKeys(2048); err == nil {
			instance, err = util.NewRsaKeys(string(pubKey), string(priKey))
		}
		return err
	}); err != nil {
		core.Logger.Panic("fail to gen rsa keys", zap.Error(err))
	}

	MdlRsa = partner.NewCommonModel()

	_ = MdlRsa.RegisterGinHandler(http.MethodGet, "/rsa/pub-key", func(c *gin.Context) {
		partner.WriteJsonSuccess(c, instance.PublicKeyStr)
	})

	core.Engine.RouterWithModel(core.ApiGroup, MdlRsa)
}
